package com.keshi.edu.mvcframework.servlet;

import com.keshi.edu.mvcframework.annotations.KsAutowired;
import com.keshi.edu.mvcframework.annotations.KsController;
import com.keshi.edu.mvcframework.annotations.KsRequestMapping;
import com.keshi.edu.mvcframework.annotations.KsService;
import com.keshi.edu.mvcframework.pojo.Handler;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class KSDispatcherServlet extends HttpServlet {
    //定义一个配置类，用于存储配置文件中的内容
    private Properties properties = new Properties();
    private List<String> classNames = new ArrayList<String>();//缓存扫描到的类的全限定类名
    //ioc容器
    private Map<String, Object> ioc = new HashMap<String, Object>();
    //HandlerMapping处理器映射器，用于存储url和Method的映射关系
//    private Map<String, Method> handlerMapping = new HashMap<String, Method>();
    private List<Handler> handlerMapping = new ArrayList<Handler>();
    @Override
    public void init(ServletConfig config) throws ServletException {
        //1.加载配置文件 springmvc.properties
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        System.out.println("contextConfigLocation:"+contextConfigLocation);
        doLoadConfig(contextConfigLocation);
        //2.扫描所有相关的类，扫描注解
        doScan(properties.getProperty("scanPackage"));
        //3.初始化bean对象（实现ioc容器，基于注解）
        doInstance();
        //4.实现依赖注入
        doAutowired();
        //5.构造一个HandlerMapping处理器映射器，将配置好的url和Method建立映射关系
        initHandlerMapping();
        System.out.println("mvc 初始化完成...");

        //等待请求进入，处理请求。
    }

    //构造一个HandlerMapping处理器映射器，将配置好的url和Method建立映射关系
    private void initHandlerMapping() {
        if (ioc.isEmpty()) return;

        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            //获取ioc中当前遍历的对象的class类型
            Class<?> aClass = entry.getValue().getClass();

            if(!aClass.isAnnotationPresent(KsController.class)){continue;}

            String baseUrl = "";
            if(aClass.isAnnotationPresent(KsRequestMapping.class)){
                KsRequestMapping annotation = aClass.getAnnotation(KsRequestMapping.class);
                baseUrl = annotation.value();
            }

            //获取方法
            Method[] methods = aClass.getMethods();
            for (int i = 0; i < methods.length; i++) {
                Method method = methods[i];

                //方法没有标识LagouRequestMapping,就不处理
                if(!method.isAnnotationPresent(KsRequestMapping.class)){continue;}

                //如果标识，就处理
                KsRequestMapping annotation = method.getAnnotation(KsRequestMapping.class);
                String methodUrl = annotation.value();
                String url=baseUrl+methodUrl;//计算出来的url

                //把method所有信息及url封装为一个handler
                Handler handler = new Handler(entry.getValue(),method, Pattern.compile(url));
    
                //计算方法的参数信息
                Parameter[] parameters = method.getParameters();
                for (int j = 0; j < parameters.length; j++) {
                    Parameter parameter = parameters[j];

                    if(parameter.getType()==HttpServletRequest.class || parameter.getType()==HttpServletResponse.class){
                        handler.getParamIndexMapping().put(parameter.getType().getName(),j);
                    }else{
                        handler.getParamIndexMapping().put(parameter.getName(),j);
                    }
                }
    

                handlerMapping.add(handler);
            }
        }
    }

    //实现依赖注入
    private void doAutowired() {
        if (ioc.isEmpty()) return;

        //有对象，再进行依赖注入处理

        //遍历ioc容器中的对象，判断对象的属性是否有@KsAutowired注解，如果有，就进行依赖注入
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            //获取bean对象中的字段信息
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
            //遍历判断处理
            for (Field declaredField : declaredFields) {
                if (!declaredField.isAnnotationPresent(KsAutowired.class)) {
                    continue;
                }

                //有该注解，就进行依赖注入
                KsAutowired annotation = declaredField.getAnnotation(KsAutowired.class);
                String beanName = annotation.value();//需要注入的bean的id
                if("".equals(beanName.trim())){
                    //没有配置具体的id，就根据类型注入
                    beanName = declaredField.getType().getName();
                }
                //开启赋值
                declaredField.setAccessible(true);
                try {
                    declaredField.set(entry.getValue(), ioc.get(beanName));
                }catch (IllegalAccessException e){
                    e.printStackTrace();
                }
            }
        }
    }

    //初始化bean对象（实现ioc容器，基于注解）
    //基于classNames缓存的类的全限定类名，以及反射技术，完成对象创建和管理
    private void doInstance() {
        if (classNames.isEmpty()) return;
        try {
            for (int i = 0; i < classNames.size(); i++) {
                String className = classNames.get(i);    //com.keshi.edu.controller.DemoController
                //反射创建对象
                Class<?> aClass = Class.forName(className);
                //区分controller，service
                if (aClass.isAnnotationPresent(KsController.class)) {
                    //controller的id此处不做过多处理，不取value了，就拿类的首字母小写作为id,保存到ioc中
                    String simpleName = aClass.getSimpleName();
                    String lowerFirstCase = lowerFirst(simpleName);//demoController
                    Object o = aClass.newInstance();
                    ioc.put(lowerFirstCase, o);
                } else if (aClass.isAnnotationPresent(KsService.class)) {
                    KsService annotation = aClass.getAnnotation(KsService.class);
                    //获取注解value的值
                    String beanName = annotation.value();

                    //如果指定了id，就以指定的为准
                    if (!"".equals(beanName.trim())) {
                        ioc.put(beanName, aClass.newInstance());
                    } else {
                        //如果没有指定id，就以类名的首字母小写作为id
                        String lowerFirstCase = lowerFirst(aClass.getSimpleName());//demoService
                        ioc.put(lowerFirstCase, aClass.newInstance());
                    }
                    //service层往往都是有接口的，面向接口开发，所以我们要把接口也保存到ioc容器中
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (Class<?> anInterface : interfaces) {//可能有多个接口
                        //以接口的全限定类名作为id，保存到ioc容器中
                        ioc.put(anInterface.getName(), aClass.newInstance());
                    }
                } else {
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //将类名首字母小写
    private String lowerFirst(String simpleName) {
        char[] chars = simpleName.toCharArray();
        if ('A' <= chars[0] && chars[0] <= 'Z') {
            chars[0] += 32;
        }
        return String.valueOf(chars);
    }

    //扫描类
    //scanPackage:com.keshi.edu package------>磁盘上的文件夹（File）

    private void doScan(String scanPackage) {
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
        File pack = new File(scanPackagePath);

        File[] files = pack.listFiles();

        for (File file : files) {
            if (file.isDirectory()) { //子package
                //递归
                doScan(scanPackage + "." + file.getName());
            } else if (file.getName().endsWith(".class")) {
                String className = scanPackage + "." + file.getName().replace(".class", "");
                classNames.add(className);
            }
        }

    }

    //加载配置文件
    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //处理请求，根据url找到对应的方法，然后调用方法
        //1.获取请求的uri
       /* String requestURI = req.getRequestURI();
        Method method = handlerMapping.get(requestURI);
        //反射调用，需要传入对象，需要传入参数，此处无法完成调用，没有把对象缓存起来，也没有参数！！！改造initHandlerMapping();
        method.invoke();*/

        //根据请求的uri，找到对应的方法
        Handler handler = getHandler(req);
        if (handler == null) {
            resp.getWriter().write("404 Not Found");
            return;
        }

        //参数绑定
        //获取所有参数类型数组，这个数组的长度就是我们最后要传入的args数组的长度
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();

        //根据上述数组长度创建一个新的数组(参数数组，是要传入反射调用的)
        Object[] paraValues=new Object[parameterTypes.length];

        //以下就是为了向参数数组中填充数据，而且还得保证参数的顺序和方法中的形参顺序一致

        Map<String, String[]> parameterMap = req.getParameterMap();

        //遍历参数数组
        for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
            //name=1&name=2&name=3 name[1,2,3]
            String value = StringUtils.join(param.getValue(), ",");

            //如果参数和方法中的参数匹配上了，就把参数值填充到参数数组中
            if(!handler.getParamIndexMapping().containsKey(param.getKey())){continue;}
            Integer index = handler.getParamIndexMapping().get(param.getKey());//name在第二个位置
            paraValues[index]=value;//把前台传递过来的参数值填充到参数数组中

        }

        int requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        paraValues[requestIndex]=req;

        int responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        paraValues[responseIndex]=resp;

        try {
            handler.getMethod().invoke(handler.getController(),paraValues);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    public Handler getHandler(HttpServletRequest req) {
        if (handlerMapping.isEmpty()) return null;
        String url = req.getRequestURI();
        for (Handler handler : handlerMapping) {
            Matcher matcher = handler.getPattern().matcher(url);
            if(!matcher.matches()){continue;}
            return handler;
        }
        return null;
    }


}
